<template>
  <div>
    <el-switch
      v-model="draggable"
      active-text="开启拖拽"
      inactive-text="关闭拖拽"
    ></el-switch>
    <el-button v-if="draggable" @click="batchSave" type="primary" size="mini"
      >批量保存</el-button
    >
    <el-button type="danger" @click="batchDelete" size="mini"
      >批量删除</el-button
    >
    <el-tree
      :data="menu"
      :props="defaultProps"
      :expand-on-click-node="false"
      show-checkbox
      node-key="catId"
      :default-expanded-keys="expandedKeys"
      :draggable="draggable"
      :allow-drop="allowDrop"
      @node-drop="handleDrop"
      :highlight-current="true"
      ref="tree"
    >
      <span class="custom-tree-node" slot-scope="{ node, data }">
        <span>{{ node.label }}</span>
        <span>
          <el-button
            v-if="node.level <= 2"
            type="primary"
            size="mini"
            icon="el-icon-circle-plus"
            plain
            @click="() => append(data)"
          > 
          </el-button>
          <el-button
            type="warning"
            size="mini"
            icon="el-icon-edit"
            plain
            @click="() => edit(data)"
          >
          </el-button>
          <el-button
            v-if="node.childNodes == 0"
            type="danger"
            size="mini"
            icon="el-icon-delete"
            plain
            @click="() => remove(node, data)"
          >
          </el-button>
        </span>
      </span>
    </el-tree>
    <el-dialog :visible.sync="dialogFormVisible" :title="boxTitle">
      <el-form :model="category">
        <el-form-item label="分类名称">
          <el-input v-model="category.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="图标">
          <el-input v-model="category.icon" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="计量单位">
          <el-input
            v-model="category.productUnit"
            autocomplete="off"
          ></el-input>
        </el-form-item>
      </el-form>
      <span class="dialog-footer" slot="footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button
          type="primary"
          @click="optionType == 'add' ? addCategory() : editCategory()"
          >确定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>
<script>
import Vue from "vue";
export default {
  components: {},
  props: {},
  data() {
    return {
      category: {
        name: "",
        parentCid: 0,
        catLevel: 1,
        showStatus: 1,
        sort: 0,
        catId: null,
        icon: "",
        productUnit: "",
      },
      draggable: false,
      pCid: [],
      updateNodes: [],
      maxLevel: 0,
      boxTitle: "",
      dialogFormVisible: false,
      optionType: "",
      menu: [],
      expandedKeys: [],
      defaultProps: {
        children: "children",
        label: "name",
      },
    };
  },
  watch: {},
  computed: {},
  methods: {
    getMenus() {
      this.$http({
        url: this.$http.adornUrl("/product/category/list/tree"),
        method: "get",
      }).then(({ data }) => {
      //  console.log(data.data);
        this.menu = data.data;
      });
    },
    append(data) {
      this.boxTitle = "新增菜单";
      this.category.name = "";
      this.category.icon = "";
      this.category.productUnit = "";
      this.category.parentCid = data.catId;
      this.category.catLevel = data.catLevel * 1 + 1;
      this.optionType = "add";
      this.dialogFormVisible = true;
    //  console.log("append", data);
    },
    edit(data) {
      this.optionType = "edit";
      // 请求后台数据，回显到页面上
      this.$http({
        url: this.$http.adornUrl(`/product/category/info/${data.catId}`),
        method: "get",
      }).then(({ data }) => {
      //  console.log(data.category);
        this.category.catId = data.data.catId;
        this.category.name = data.data.name;
        this.category.icon = data.data.icon;
        this.category.productUnit = data.data.productUnit;
        this.boxTitle = "修改菜单";
        //重新给父ID 赋值，否则展开时获取的是默认父ID
        this.category.parentCid = data.data.parentCid;
        this.dialogFormVisible = true;
      });
    },
    remove(node, data) {
      this.$confirm(`是否删除【${data.name}】菜单?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          var ids = [data.catId];
        //  console.log("remove", node, data);
          this.$http({
            url: this.$http.adornUrl("/product/category/delete"),
            method: "post",
            data: this.$http.adornData(ids, false),
          }).then(({ data }) => {
            this.getMenus();
            this.expandedKeys = [node.parent.data.catId];
            // const parent = node.parent;
            // const children = parent.data.children || parent.data;
            // const index = children.findIndex((d) => d.id === data.id);
            // console.log("index"+index+"<parent"+parent+"data"+data);
            // children.splice(index, 1);
            this.$message({
              message: "菜单删除成功",
              type: "success",
              center: true,
            });
          });
        })
        .catch(() => {});
    },
    editCategory() {
      var { catId, name, productUnit, icon,parentCid ,showStatus,catLevel} = this.category;
      // var data =  {catId:catId,name:name,productUnit:productUnit,icon:icon};
      // 如果key name 和 value name 一致  则可以简写
      var data = { catId, name, productUnit, icon,parentCid,showStatus,catLevel };

      this.$http({
        url: this.$http.adornUrl("/product/category/update"),
        method: "post",
        data: this.$http.adornData(data, false),
      }).then(({ data }) => {
        this.getMenus();
        this.expandedKeys = [this.category.parentCid];
      });
      this.dialogFormVisible = false;
    },
    addCategory() {
      this.$http({
        url: this.$http.adornUrl("/product/category/save"),
        method: "post",
        data: this.$http.adornData(this.category, false),
      }).then(({ data }) => {
        this.getMenus();
        this.expandedKeys = [this.category.parentCid];
      //  console.log("添加成功");
      });
      this.dialogFormVisible = false;
    },
    allowDrop(draggingNode, dropNode, type) {
      //被拖动的当前节点 以及所在的父节点总层数不能大于3
      //console.log("allowDrop", draggingNode, dropNode, type);
      //统计当前节点层级
      this.countNodeLevel(draggingNode.data);
      var deep = this.maxLevel - draggingNode.level + 1;
      //  console.log(this.maxLevel + "当前深度", deep);
      if (type == "inner") {
        return deep + dropNode.level <= 3;
      } else {
        return deep + dropNode.parent.level <= 3;
      }
    },
    countNodeLevel(node) {
      if (node.children != null && node.children.length > 0) {
        for (let i = 0; i < node.children.length; i++) {
          if (node.children[i].catLevel > this.maxLevel) {
            this.maxLevel = node.children[i].catLevel;
          }
          this.countNodeLevel(node.children[i]);
        }
      }
    },
    handleDrop(draggingNode, dropNode, dropType, ev) {
      //1、当前节点最新的父节点id
      let pcid = 0;
      let siblings = null;
      if (dropType == "before" || dropType == "after") {
        pcid =
          dropNode.parent.data.catId == undefined
            ? 0
            : dropNode.parent.data.catId;
        siblings = dropNode.parent.childNodes;
      } else {
        pcid = dropNode.data.catId;
        siblings = dropNode.childNodes;
      }
      this.pCid.push(pcid);
      //拖拽后的当前节点的最新层级
      for (let i = 0; i < siblings.length; i++) {
        if (siblings[i].data.catId == draggingNode.data.catId) {
          //遍历的当前节点正是被拖拽的节点  需要修改parentcid 和sort 、层级leve
          let catLevel = draggingNode.level;
          if (draggingNode.level != siblings[i].level) {
            //被拖拽的节点层级修改了
            catLevel = siblings[i].level;
            //递归修改子节点的层级
            this.updateChildNodeLevel(siblings[i]);
          }
          this.updateNodes.push({
            catId: siblings[i].data.catId,
            parentCid: pcid,
            sort: i,
            catLevel: catLevel,
          });
        } else {
          this.updateNodes.push({ catId: siblings[i].data.catId, sort: i });
        }
      }
    //  console.log(this.updateNodes);
    },
    updateChildNodeLevel(nodes) {
      for (let i = 0; i < nodes.childNodes.length; i++) {
        var node = nodes.childNodes[i].data;
        this.updateNodes.push({
          catId: node.catId,
          catLevel: nodes.childNodes[i].catLevel,
        });
      }
    },
    batchSave() {
      this.$http({
        url: this.$http.adornUrl("/product/category/update/sort"),
        method: "post",
        data: this.$http.adornData(this.updateNodes, false),
      }).then(({ data }) => {
        this.$message({
          message: "菜单顺序等修改成功",
          type: "success",
        });
        //刷新出新的菜单
        this.getMenus();
        //设置需要默认展开的菜单
        this.expandedKeys = this.pCid;
        this.updateNodes = [];
        this.maxLevel = 0;
        // this.pCid = 0;
      });
    },
    batchDelete() {
      let catIds = [];
      let checkedNodes = this.$refs.tree.getCheckedNodes();
     // console.log("被选中的元素", checkedNodes);
      for (let i = 0; i < checkedNodes.length; i++) {
        catIds.push(checkedNodes[i].catId);
      }
      if (catIds.length > 0) {
        this.$confirm(`是否批量删除菜单?`, "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            this.$http({
              url: this.$http.adornUrl("/product/category/delete"),
              method: "post",
              data: this.$http.adornData(catIds, false),
            }).then(({ data }) => {
              this.$message({
                message: "菜单批量删除成功",
                type: "success",
              });
              this.getMenus();
            });
          })
          .catch(() => {});
      } else {
        this.$notify.error({
          title: "提示",
          message: "请选择删除的菜单",
        });
      }
    },
  },
  created() {
    this.getMenus();
  },
  mounted() {},
  beforeCreate() {},
  beforeMount() {},
  beforeUpdate() {},
  updated() {},
  beforeDestroy() {},
  destroyed() {},
  activated() {},
};
</script>
<style scoped>
 .custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
} 
.el-button--mini,
.el-button--mini.is-round {
  padding: 5px 10px;
  margin-left: 4px;
} 

</style>